package com.dailyblue.java.servlet.controller;

import com.dailyblue.java.servlet.bean.Goods;
import lombok.SneakyThrows;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@WebServlet("/session")
public class SessionController extends ReflectionController {
    @SneakyThrows
    public void goods(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().setAttribute("GOODS", find());
        response.sendRedirect("session/goods.jsp");
    }

    @SneakyThrows
    public void cart(HttpServletRequest request, HttpServletResponse response) {
        // 获取到你要加入购物车的商品ID
        int id = Integer.parseInt(request.getParameter("id"));
        // 找到商品
        Goods goods = find(id);
        // 把这个商品放入到购物车中
        List<Goods> carts;
        HttpSession session = request.getSession();
        Object obj = session.getAttribute("CART");
        if (obj == null) {
            // 如果不存在，则创建这个购物车
            carts = new ArrayList<>(); // 目前的集合是空集合
        } else {
            // 如果存在，则使用这个购物车
            carts = (List<Goods>) obj; // 类型转换
        }
        // 把商品放入购物车
        // 引入数量的概念，如果集合中没有商品，加入购物车；如果有，数量自增1
        int index = find(carts, goods);
        if (index == -1) {
            carts.add(goods);
        } else {
            System.out.println("找到的位置是：" + index);
            Goods g = carts.get(index);
            g.setNum(g.getNum() + 1);
        }

        // 再把购物车存放到session
        session.setAttribute("CART", carts);
        // 跳转到页面
        response.sendRedirect("session/goods.jsp");
    }

    // 模拟假的一些商品
    private List<Goods> find() {
        List<Goods> list = new ArrayList<>();
        Goods g1 = new Goods(1, "键盘", 23.2);
        Goods g2 = new Goods(2, "鼠标", 13.8);
        Goods g3 = new Goods(3, "可口可乐", 2.3);
        Goods g4 = new Goods(4, "水杯", 11.9);
        Goods g5 = new Goods(5, "手机", 1998.2);
        list.add(g1);
        list.add(g2);
        list.add(g3);
        list.add(g4);
        list.add(g5);
        return list;
    }

    private Goods find(int id) {
        List<Goods> list = find();
        for (int i = 0; i < list.size(); i++) {
            Goods g = list.get(i);
            if (g.getId() == id) {
                return g;
            }
        }
        return null;
    }

    private int find(List<Goods> list, Goods goods) {
        for (int i = 0; i < list.size(); i++) {
            Goods g = list.get(i);
            if (Objects.equals(g.getId(), goods.getId())) {
                return i;
            }
        }
        return -1;
    }
}
